const booksModule = {
    init() {
        this.loadBooks();
    },

    loadBooks() {
        fetch(`${API_BASE_URL}/books`)
            .then(response => response.json())
            .then(books => {
                const html = `
                    <div class="d-flex justify-content-between align-items-center">
                        <h2>图书管理</h2>
                        <button type="button" class="btn btn-primary" id="addBookBtn">添加图书</button>
                    </div>
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>ISBN</th>
                                    <th>书名</th>
                                    <th>作者</th>
                                    <th>出版社</th>
                                    <th>价格</th>
                                    <th>库存</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${books.map(book => `
                                    <tr>
                                        <td>${book.isbn}</td>
                                        <td>${book.title}</td>
                                        <td>${book.author}</td>
                                        <td>${book.publisher}</td>
                                        <td>￥${book.price}</td>
                                        <td>${book.stock}</td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="btn btn-sm btn-warning update-stock" data-id="${book.id}">
                                                    修改库存
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                $('#main-content').html(html);

                // 绑定事件
                $('#addBookBtn').on('click', () => this.showAddBookForm());
                $('.update-stock').on('click', (e) => {
                    const bookId = $(e.target).data('id');
                    this.updateStock(bookId);
                });
            })
            .catch(handleError);
    },

    showAddBookForm() {
        const html = `
            <div class="form-container">
                <h3>添加新图书</h3>
                <form id="addBookForm" class="needs-validation" novalidate>
                    <div class="mb-3">
                        <label class="form-label">ISBN</label>
                        <input type="text" class="form-control" name="isbn" required>
                        <div class="invalid-feedback">请输入ISBN</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">书名</label>
                        <input type="text" class="form-control" name="title" required>
                        <div class="invalid-feedback">请输入书名</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">作者</label>
                        <input type="text" class="form-control" name="author" required>
                        <div class="invalid-feedback">请输入作者</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">出版社</label>
                        <input type="text" class="form-control" name="publisher" required>
                        <div class="invalid-feedback">请输入出版社</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">价格</label>
                        <input type="number" class="form-control" name="price" step="0.01" min="0" required>
                        <div class="invalid-feedback">请输入有效的价格</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">库存</label>
                        <input type="number" class="form-control" name="stock" min="0" required>
                        <div class="invalid-feedback">请输入有效的库存数量</div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">提交</button>
                        <button type="button" class="btn btn-secondary" onclick="booksModule.loadBooks()">返回</button>
                    </div>
                </form>
            </div>
        `;
        $('#main-content').html(html);

        // 表单验证和提交
        const form = document.getElementById('addBookForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            if (!form.checkValidity()) {
                e.stopPropagation();
                form.classList.add('was-validated');
                return;
            }

            const formData = new FormData(e.target);
            const book = Object.fromEntries(formData.entries());
            // 转换数字类型
            book.price = parseFloat(book.price);
            book.stock = parseInt(book.stock);
            
            fetch(`${API_BASE_URL}/books`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(book)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加图书失败');
                }
                return response.json();
            })
            .then(() => {
                alert('添加成功！');
                this.loadBooks();
            })
            .catch(handleError);
        });
    },

    updateStock(bookId) {
        const quantity = prompt('请输入要增加的库存数量（减少请输入负数）：');
        if (quantity === null) return;

        fetch(`${API_BASE_URL}/books/${bookId}/stock?quantity=${quantity}`, {
            method: 'PUT'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新库存失败');
            }
            alert('库存更新成功！');
            this.loadBooks();
        })
        .catch(handleError);
    }
}; 